#!/usr/bin/env perl
use warnings;
use strict;

# Given a file like big.movies.with_ids (first arg) and an adjacency list like
# big.adj (standard in), count the number of links on each movie page.

scalar(@ARGV) == 1 or die "need with_ids file as argument";
my ($with_ids_file) = @ARGV;
-e$with_ids_file  or die "input file $with_ids_file not found";

open(my $fh, "<$with_ids_file");
my @with_ids_lines = <$fh>;
close($fh);

# Use a hash of integers for reasonable efficiency.
# We actually reverse the mapping in the file, which should be 1:1.
my %with_ids = map {
  # $1 is the movie ID, $2 is the page id.
  /(\d+)\s+(\d+)/ or die "unexpected with_ids line format: $_";
  int($2) => int($1)
} @with_ids_lines;

# Read adj list.
while (<STDIN>) {
  /(\d+)\s+(\d+).*/ or die "invalid adj line format: $_";
  my $page_num = $1;
  my $link_count = $2;
  my $movie_id = $with_ids{$page_num};
  if (defined($movie_id)) {
    print "$movie_id $link_count\n";
  }
}

# Copyright (c) 2009 John Lees-Miller
# 
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.

